package be.sc.classicnetwork.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import freemarker.template.SimpleHash;

import be.sc.classicnetwork.form.Request;
import be.sc.classicnetwork.util.PropertiesUtils;

public class RequestFormController extends AbstractFormController {

	private static final String REQUEST_TEMPLATE = "request.ftl";

	/**
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new Request();
	}

	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Request req = (Request) command;

		// put the request info as model for freemarker template
		SimpleHash model = new SimpleHash();
		model.put("request", req);

		// get some application properties
		String from = PropertiesUtils.MAIL_FROM;
		String fromPersonal = PropertiesUtils.MAIL_FROM_PERSONAL;
		String subjectPrefix = PropertiesUtils.MAIL_SUBJECT_PREFIX;

		// send the email
		getServiceLocator().getMailService().sendFreeMarkerTemplate(from,
				fromPersonal, from,
				subjectPrefix + " Request: " + req.getSubject(), null,
				REQUEST_TEMPLATE, model);

		// show confirmation message
		return new ModelAndView("info", "text",
				"A representative of Classic Network will contact you very shortly");
	}

}
